package com.wolfking.jeesite.freemarker.tag;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.wolfking.jeesite.freemarker.FreemarkerTag;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * freemarker的treeview的tag
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月28日下午3:50:30
 * @版权 归wolfking所有
 */
@FreemarkerTag("page")
@SuppressWarnings({"rawtypes", "unchecked"})
public class PageTag implements TemplateDirectiveModel {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        if (params != null) {
            Set<Map.Entry> set = params.entrySet();
            for (Map.Entry entry : set) {
                if (entry.getKey().toString().equals("pageJson")) {
                    env.getCurrentNamespace().put("ftPage",
                            objectMapper.readValue(entry.getValue().toString(), PageInfo.class));
                } else {
                    env.getCurrentNamespace().put(entry.getKey().toString(), entry.getValue());
                }
            }
            body.render(env.getOut());
        }
    }
}
